package com.cn.demo.config;

import com.cn.demo.util.CommonConstants;
import org.redisson.api.RRateLimiter;
import org.redisson.api.RateIntervalUnit;
import org.redisson.api.RateType;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

/**
 * 秒杀限流器
 * 采用分布式限流器redisson进行实现
 *
 * @author wangjf
 * @version 1.0
 * @createDate 2019/11/15 11:32
 * @projectName test
 */
@Component
public class SeckillRRateLimiter implements InitializingBean {

    @Autowired
    private RedissonClient redisson;
    private RRateLimiter rateLimiter;

    @Override
    public void afterPropertiesSet() throws Exception {
        if (rateLimiter == null) {
            rateLimiter = redisson.getRateLimiter("seckillRateLimiter");
            rateLimiter.delete();
            rateLimiter.trySetRate(RateType.OVERALL, CommonConstants.API_LIMITER_RATE, 1, RateIntervalUnit.SECONDS);
        }
        Assert.notNull(rateLimiter, "秒杀限流器初始化失败, seckillRateLimiter is null");
    }


    /**
     * 返回限流器对象
     * @author: wangjf
     * @createTime: 2019/11/15 11:36
     * @param
     * @return org.redisson.api.RRateLimiter
     */
    public RRateLimiter getRRateLimiter(){
        return rateLimiter;
    }

    /**
     * 尝试获取许可，有可用的则返回true
     * @author: wangjf
     * @createTime: 2019/11/15 11:36
     * @param
     * @return java.lang.Boolean
     */
    public Boolean tryAcquire(){
        return rateLimiter.tryAcquire();
    }

    /**
     * 消费许可
     * @author: wangjf
     * @createTime: 2019/11/15 11:38
     * @param
     * @return void
     */
    public void acquire(){
        rateLimiter.acquire();
    }


}
